<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:th="http://www.thymeleaf.org">
<head th:include="_header_include::frag(~{::title},~{},~{::style})">
    <title>区域管理</title>
    <style>
        .organizationManage .leftBox{/*width: 200px;*/height: auto;border:1px solid #ebeef5;min-height: 480px;}
        .organizationManage .leftTitle{background:#c0defc;text-indent: 20px;height: 40px;line-height: 40px;}
        .organizationManage .leftTree{padding:10px;}
        .organizationManage .rightTitle{background:#c0defc;padding-left: 20px;height: 40px;line-height: 40px;}
        .el-dialog {width: 650px;}
        /*20190419*/
        .organizationManage .leftTitle, .organizationManage .rightTitle { color: #ffffff;background-color: #5c6be8; border-color: #5c6be8;border-top-left-radius: 4px;border-top-right-radius: 4px; }
    </style>
</head>
<body>
<div id="organizationManage" class="organizationManage mainPadding" style="display:none">
    <el-breadcrumb separator="/" class="elBreadcrumb marginB20">
        <el-breadcrumb-item>Home</el-breadcrumb-item>
        <el-breadcrumb-item>系统管理</el-breadcrumb-item>
        <el-breadcrumb-item>区域管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-row :gutter="20">
        <el-col :span="5">
            <div class="leftBox">
                <div class="leftTitle fs16">区域列表</div>
                <el-tree
                    :data="dataTree"              
                    node-key="id"
                    :default-expanded-keys="expandedKeys"
                    ref="tree"
                    highlight-current
                    :expand-on-click-node=false
                    @node-click="clickOrgNode"
                    @selection-change="handleSelectionChange"
                    class="leftTree">
                </el-tree>
            </div>            
        </el-col>
        <el-col :span="19">
            <el-row class="marginB20">
                <el-col :span="17">
                    <el-button type="primary" @click="addChildOrg"><i class="el-icon-plus"></i>添加下级区域</el-button>
                    <el-button type="success" @click="modifyChildOrg"><i class="el-icon-edit"></i>编辑</el-button>
                    <el-button type="danger" @click="deleteFun"><i class="el-icon-delete"></i>删除</el-button>                    
                </el-col>
                <el-col :span="7">
                    <el-input placeholder="请输入区域名称进行查询" class="input-with-select searchBox" v-model="inputOrgName">
                      <el-button slot="append" icon="el-icon-search" @click="getQuery">搜索</el-button>
                    </el-input>
                </el-col>
            </el-row>
            <el-row class="rightTitle fs16"> {{form.parentName}} 下一级区域</el-row>
            <div class="mainSearchBg">
              <el-row>
                  <el-table 
                      ref="multipleTable"
                      tooltip-effect="dark"
                      empty-text="此区域无下级区域"
                      style="width: 100%"
                      @selection-change="handleSelectionChange"
                      border
                      :data="dataTable"
                      >
                      <el-table-column align="center" prop="id"  type="selection" width="55"></el-table-column> 
                       <el-table-column align="center" prop="type" type="index" width="55" label="序号"></el-table-column> 
                      <el-table-column align="center" prop="name" label="区域名称"></el-table-column>                      
                  </el-table>
                   <table-pagination :pager="pager" @change="getQuery"></table-pagination>
              </el-row>
          </div>
        </el-col>
    </el-row>
    <!-- dialog -->
    <el-dialog :title="addOrModifyDialogTitle" :visible.sync="dialogFormVisible" @close="closeAddOrgDialog" width="540px">
        <el-form :model="form"  ref="ruleForm" :rules="rules">
            <el-form-item label="上一级区域：" :label-width="formLabelWidth" prop="parentName">
                   {{form.parentName}}
            </el-form-item> 
            <el-form-item label="区域名称：" :label-width="formLabelWidth" prop="name" >
                <el-input v-model="form.name"  autocomplete="off" maxlength="50"   placeholder="输入名称" style="width:80%;"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align:center;">
            <el-button :disabled="confirmBtnDisabled" type="primary" @click="submitForm('ruleForm')">确 定</el-button>
            <el-button @click="cancelForm('ruleForm')">取 消</el-button>            
        </div>
    </el-dialog>  
    
    <el-dialog title="组内成员" :visible.sync="dialogStaffNumVisible" @close="closeStaffNumDialog">
        <el-row>
		 <el-form :inline="true" :model="staffNumSearch" class="demo-form-inline" ref="staffNumSearch"> 
		      <el-form-item label="" prop="name">
                  <el-input v-model="staffNumSearch.name" placeholder="姓名"></el-input> 
              </el-form-item> 
               <el-form-item label="" prop="username"> 
                 <el-input v-model="staffNumSearch.username" placeholder="登录名"></el-input> 
              </el-form-item>
               <el-form-item label="" prop="phone"> 
                 <el-input v-model="staffNumSearch.phone" placeholder="手机号"></el-input> 
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="initStaffNumTable">搜索</el-button> 
              </el-form-item> 
         </el-form>
        </el-row>
             <el-row>
                <el-table 
                    ref="staffNumTable"
                    tooltip-effect="dark"
                    empty-text="无数据"
                    style="width: 100%"
                    border
                    :data="staffNumTable" 
                    >
                    <el-table-column align="center" prop="id" type="selection" width="55"></el-table-column> 
                     <el-table-column align="center" type="index" width="100" label="序号"></el-table-column>
                     <!-- <el-table-column prop="date" label="全选" width="180"></el-table-column>  -->
                    <el-table-column align="center" prop="name" label="姓名"></el-table-column>
                   
                </el-table>
                 <table-pagination :pager="pagerStaffNum" @change="initStaffNumTable"></table-pagination>
            </el-row>
         
         
      </el-dialog>
    
    
</div>
</body>
<!-- import common js-->
<div th:include="_footer_include :: #jsLib"></div>
<script th:inline="javascript">
    var orgData=[[${orgData}]];
    var expandedKeys =[];//默认展开节点
    for(var i=0;i<orgData.length;i++){
    	var curNode = orgData[i];
    	expandedKeys.push(curNode.id);
    	var childs = curNode.children;
    	if(childs){
    		for(var j=0;j<childs.length;j++){
    			var curChildNode = childs[j];
    			expandedKeys.push(curChildNode.id);
    		}
    	}
    	
    }
    var orgVM =  new Vue({
        el: '#organizationManage',
        data: function() {
            return {
            	confirmBtnDisabled:false,
            	expandedKeys:expandedKeys,//树形结构  默认展开的
                dataTree: orgData,//组织结构tree
                dataTable:[],//
                staffNumTable:[],//组织人员table
                multipleSelection: [],//选择行
                defaultProps: {
                    children: 'children',
                    label: 'label'
                  },
                dialogFormVisible: false,
                dialogStaffNumVisible:false,
                addOrModifyDialogTitle:'',//条件或修改组织机构标题
                submitUrl:'',//添加组织机构 url
                form: {//添加组织机构dialog
                    name: '',
                    remark: '',
                    parentName:'',
                    id:''
                },
                staffNumSearch:{//组内组成搜索框
                	name:'',
                	userName:'',
                	phone:''
                },
                oldName:'',//旧的组织机构，更新时使用 
                formLabelWidth: '120px',
                pager:{//组织列表pager
                    total: 0,
                    currentPage: 1,
                    pageSize: 20,
                },
                pagerStaffNum:{//组内成员pager
                    total: 0,
                    currentPage: 1,
                    pageSize: 20,
                },
                selectedNode:null,//当前的orgParentId
                selectedOrgId:'',//组织列表中，点击的是个组织 
                rules:{
                	 name: [
                         { required: true, message: '区域名称不能为空',trigger:'blur'},
                         { validator:function(rule,value,callback){
                        	 var id = orgVM.form.id;
                        	 var name = orgVM.oldName;
                        	 if(id && value==name){
                        		 callback();
                        	 }
                        	 var  parentId = orgVM.selectedNode.id;
                               var param = {};
                               param.name=value;
                               param.parentId = parentId;
                        	    axios.post('/area/sysregion/queryOrgByParam',param)
                                .then(function (response) {
                                    var data =  response.data
                                    if(data.code=='0'){
                                        var resData = data.data;
                                        if(resData){
                                        	callback(new Error("区域名称已存在，请更改"));
                                        }else{
                                        	callback();
                                        }
                                        
                                    }else{
                                    	 callback(new Error("查询区域名称是否唯一报错"));
                                    }
                                })
                                .catch(function (error) {
                                  console.log(error);
                                })
                                .then(function () {
                                  // always executed
                                });
                               
                        },trigger: 'blur'}
                     ]
                },
                inputOrgName:'',//搜索框 组织名称
                multipleSelection:[],//选择的列
            }             
        },
        methods: {
            toggleSelection(rows) {
                if (rows) {
                    rows.forEach(row => {
                        this.$refs.multipleTable.toggleRowSelection(row);
                    });
                } else {
                  this.$refs.multipleTable.clearSelection();
                }
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            deleteFun() {//点击删除组织机构
            	var rows = this.multipleSelection;
            	if(rows.length==0){
                    this.$message({
                       message: '请选择一条数据进行删除',
                       type: 'warning'
                     });
                    return;
                }
                var rowIds = [];
                var strs = "";
                for(var i=0;i<rows.length;i++){
                    rowIds.push(rows[i].id);
                    if(strs ==""){
                    	strs = "【"+rows[i].name+"】"
                    }else{
                    	strs = strs+"【"+rows[i].name+"】"
                    }
                }
                var mesage ="确定要删除"+strs+"区域吗？"; 
                var param  = {idList:rowIds}
                
                this.$confirm(mesage, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                
  		           axios.post('/area/sysregion/delete',param)
                   .then(function (response) {
                	   console.info(response);
                       var data =  response.data;
                       if(data.code=='0'){
                           var resData = data.data;
                           var delText="";
                           if(resData){
                        	   delText="删除成功";
                           }else{
                               delText="删除失败"
                           }
                           
                         orgVM.$message({message:delText,type:'success',duration:2000,onClose:function(){
                        	 orgVM.initOrgTree();
                             orgVM.getQuery();
                   	    }});
                           
                       }else{
                    	   orgVM.$message({
                               message: "接口调用失败",
                               type: 'warning'
                             }); 
                       }
                   })
                   .catch(function (error) {
                     console.log(error);
                     orgVM.$message({
                         message: "系统错误",
                         type: 'error'
                       }); 
                   })
                   .then(function () {
                	   
                   });  
  	              
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });          
                });
                
            
            },
            clickOrgNode(data,node,obj){//点击左侧节点
            	this.inputOrgName = "";
            	this.selectedNode = data;
            	this.form.parentName=data.label;
            	this.form.id=data.id;
            	this.getQuery();
            },
            getQuery(){
                this.initTableData();
            },
            initTableData(){// 查询 table 需要数据
                var pageSize = this.pager.pageSize;
                var pageNum = this.pager.currentPage;
                var param = {};
                var  parentId = this.selectedNode.id;
              
                param.parentId = parentId;
                param.name = this.inputOrgName;
                param.pageNum = pageNum;
                param.pageSize = pageSize;
                axios.post('/area/sysregion/querySysRegionDTOByParam',param)
                    .then(function (response) {
                        var data =  response.data
                        if(data.code=='0'){
                        	var resData = data.data;
                        	orgVM.dataTable= resData.data;
                            //3.分页组件
                            orgVM.pager.total= resData.total;
                            orgVM.pager.currentPage = resData.currentPage;
                            orgVM.pager.pageSize = resData.pageSize;
                        }else{
                        	 orgVM.$message({
                                 message: "接口调用失败",
                                 type: 'error'
                               }); 
                        	console.error(data);
                        }
                        
                       
                    })
                    .catch(function (error) {
                      console.log(error);
                    })
                    .then(function () {
                      // always executed
                    });  
            },
            addChildOrg(){
            	this.form.id='';
            	var curData = this.selectedNode;
            	if(!curData){
            		this.$message({
                        message: '请选择一个上级',
                        type: 'warning'
                      });
                     return;
            	}
            	if (this.$refs['ruleForm']!==undefined) {
            		this.$refs['ruleForm'].clearValidate();
             	}
            	this.form.name="";
                this.addOrModifyDialogTitle="添加区域";
                this.submitUrl = 'save';
            	this.dialogFormVisible = true;
            },
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                  if (valid) {
                	  orgVM.confirmBtnDisabled = true;
                     var param=this.form;
                     param.parentId=this.selectedNode.id;
                    axios.post('/area/sysregion/'+this.submitUrl, param)
                    .then(function (response) {
                    	var resData = response.data;
                    	if(resData.code=='0'){
                    	    orgVM.$message({message:'操作成功',type:'success',duration:2000,onClose:function(){
                    	        orgVM.initOrgTree();
                         	    orgVM.getQuery();
                    	    }});
                    	    orgVM.cancelForm(formName);
                    	    orgVM.dialogFormVisible = false;
                    	    orgVM.confirmBtnDisabled = false;
                    	}else{
                            orgVM.$message('操作失败');
                            orgVM.confirmBtnDisabled = false;
                    	}
                    })
                    .catch(function (error) {
                        orgVM.confirmBtnDisabled = false;
                        console.log(error);
                    });
                     
                  } else {
                    return false;
                  }
                });
              },
              cancelForm(formName) {
                //  this.$refs[formName].resetFields();
                  this.dialogFormVisible = false;
              },
              initOrgTree(){//刷新根节点tree
            	  axios.post('/area/sysregion/query',{})
                  .then(function (response) {
                      var data =  response.data
                      if(data.code=='0'){
                          orgVM.dataTree= data.data; 
                          
                      }
                      
                     
                  })
                  .catch(function (error) {
                    console.log(error);
                  })
                  .then(function () {
                    // always executed
                  }); 
            	  
              },
              handleSelectionChange(val) {//选择节点的事件
                  this.multipleSelection = val;
              },
              modifyChildOrg(){//点击修改按钮时
            	  var rows = this.multipleSelection;
                  if(rows.length!=1){
                      this.$message({
                         message: '请选择一条数据进行修改',
                         type: 'warning'
                       });
                      return;
                  }
                  this.form.name="";
                  this.addOrModifyDialogTitle="编辑区域";
                  this.submitUrl = 'update';
                 var parentName =  orgVM.form.parentName;
                  var param={id:rows[0].id};
                  //根据id获取数据
                  axios.post('/area/sysregion/queryOrgById',param)
                  .then(function (response) {
                      var data =  response.data;
                      if(data.code=='0'){
                          orgVM.form= data.data;
                          orgVM.form.parentName=parentName;
                          //把当前的值存在临时变量里，当修改时，旧值和新值对比
                          orgVM.oldName = data.data.name;
                      }
                      
                     
                  })
                  .catch(function (error) {
                    console.log(error);
                  })
                  .then(function () {
                    // always executed
                  }); 
                  
                  
                  this.dialogFormVisible = true;
            	 
              },
              closeAddOrgDialog(){//close 添加组织弹框
            	 // alert(1);
            	 //  this.$refs['ruleForm'].resetFields();
              },
              openStaffNumTable(orgId){//打开组内成员弹框
            	   this.dialogStaffNumVisible = true;
            	   this.selectedOrgId=orgId;
            	   
            	   
            	   var param = this.staffNumSearch;
            	   param.orgId = orgId;
            	   param.pageSize = this.pagerStaffNum.pageSize;
                   param.pageNum = this.pagerStaffNum.currentPage;
           	       axios.post('/area/sysregion/listOrgUserInfo',param)
                     .then(function (response) {
                       var data =  response.data
                       if(data.code=='0'){
                       	var resData = data.data;
                       	orgVM.staffNumTable= resData.data;
                        //3.分页组件
                       	orgVM.pagerStaffNum.total= resData.total;
                       	orgVM.pagerStaffNum.currentPage = resData.currentPage;
                       	orgVM.pagerStaffNum.pageSize = resData.pageSize;
                           
                       }else{
                       	 console.error(data);
                       }
                   })
                   .catch(function (error) {
                     console.log(error);
                   })
                   .then(function () {
                     // always executed
                   });
           	    
           	    
           	    
              },
              initStaffNumTable(){
            	  
            	  this.openStaffNumTable(this.selectedOrgId); 
              },
              closeStaffNumDialog(){//
            	this.$refs['staffNumSearch'].resetFields();
            	this.selectedOrgId='';//把当前的组织ID设为''
              }
              
              
              
              
        },
       mounted(){
           document.getElementById('organizationManage').style.display = 'block';
       },
        created(){
            var localVal=localStorage.getItem('allChangePageSize')?parseInt(localStorage.getItem('allChangePageSize')):'';
            if(localVal){this.pager.pageSize = localVal;}
        	this.clickOrgNode(this.dataTree[0],null,null);
        	
        }//created方法 结束
    })
</script>
</html>